local M = {}
package.loaded[...] = M

local telescope = require'telescope'
local builtin = require'telescope.builtin'
local actions = require'telescope.actions'
local action_set = require"telescope.actions.set"
local action_state = require "telescope.actions.state"
local action_layout = require'telescope.actions.layout'
local lga_actions = require("telescope-live-grep-args.actions")

telescope.setup{
  defaults = {
    -- borderchars = { "─", "│", "─", "│", "┌", "┐", "┘", "└" },
    preview = { hide_on_startup = true },
    layout_config = { width = 0.8, height = 0.5 },
    mappings = {
      n = {
        ["<M-m>"] = action_layout.toggle_preview,
      },
      i = {
        ["<C-u>"] = false,
        ["<C-n>"] = actions.cycle_history_next,
        ["<C-p>"] = actions.cycle_history_prev,
        ["<C-s>"] = actions.preview_scrolling_up,
        ["<C-j>"] = actions.move_selection_next,
        ["<C-k>"] = actions.move_selection_previous,
        ["<esc>"] = actions.close,
        ["<M-m>"] = action_layout.toggle_preview,
        ["<C-x>"] = { actions.select_horizontal, type = "action", opts = { nowait = true } },
        ["kj"] = {"<esc>", type = "command"},
      },
    },
  },
  pickers = {
    buffers = {
      initial_mode = "normal"
    },
    oldfiles = {
      path_display = function(opts, path)
        return require"plenary.path":new(path):normalize(opts.cwd or vim.loop.cwd())
      end,
    },
    git_files = {
      show_untracked = true,
    },
    git_status = {
      initial_mode = "normal",
      preview = { hide_on_startup = false },
    },
    registers = {
      layout_config = {width = 0.8, height = 0.8},
    },
  },
  extensions = {
    fzf = {
      fuzzy = true,                    -- false will only do exact matching
      override_generic_sorter = true,  -- override the generic sorter
      override_file_sorter = true,     -- override the file sorter
      case_mode = "smart_case",        -- or "ignore_case" or "respect_case"
                                       -- the default case_mode is "smart_case"
    },
    live_grep_args = {
      auto_quoting = true,
      mappings = {
        i = {
          ["<C-o>"] = lga_actions.quote_prompt({ postfix = " --iglob " }),
          -- freeze the current list and start a fuzzy search in the frozen list
          ["<C-space>"] = actions.to_fuzzy_refine,
        }
      }
    }
  }
}

-- Load extensions
telescope.load_extension'fzf'
telescope.load_extension'live_grep_args'

M.git_files_or_find_files = function()
  local opts = {} -- define here if you want to define something
  if vim.fs.root(0, '.git') then
    builtin.git_files(opts)
  else
    builtin.find_files(opts)
  end
end

M.git_files_or_old_files = function()
  local opts = {} -- define here if you want to define something
  if vim.fs.root(0, '.git') then
    builtin.git_files(opts)
  else
    builtin.oldfiles(opts)
  end
end

vim.keymap.set("n", "<Leader>ff", "<Cmd>lua require'telescope-config'.git_files_or_find_files()<CR>", {noremap = true, silent = true})
vim.keymap.set('n', '<leader>bb', builtin.buffers, {noremap = true, silent = true})
vim.keymap.set('n', '<leader>bh', builtin.oldfiles, {noremap = true, silent = true})
vim.keymap.set('n', '<leader>ss', "<Cmd>lua require'telescope.builtin'.live_grep({cwd=vim.fs.root(0, '.git')})<CR>", {noremap = true, silent = true})
vim.keymap.set('n', '<leader>sc', "<Cmd>lua require'telescope-config'.grep_git_dir_or_curr_dir(require'telescope'.extensions.live_grep_args.live_grep_args)<CR>", {noremap = true, silent = true})
vim.keymap.set('n', '<leader>sb', builtin.current_buffer_fuzzy_find, {noremap = true, silent = true})
vim.keymap.set('n', '<leader>yr', builtin.registers, {noremap = true, silent = true})
vim.keymap.set('n', '<leader>gg', builtin.git_status, {noremap = true, silent = true})

vim.api.nvim_create_autocmd({"UIEnter"}, {
  pattern = {"*"},
  callback = function(ev)
    if
      (#vim.v.argv == 2 and vim.v.argv[2] == "--embed")
      or #vim.v.argv == 1
      or (#vim.v.argv == 3 and vim.deep_equal({unpack(vim.v.argv, 2, 3)}, {"--embed", "-p"})) -- for neovide
    then
      vim.schedule(M.git_files_or_old_files)
    end
  end,
  group = vim.api.nvim_create_augroup("OpenOldfilesListAfterStart", { clear = true })})

-- Get from https://www.petergundel.de/git/neovim/telescope/2023/03/22/git-jump-in-neovim-with-telescope.html
local git_hunks = function()
  local git_root_path = string.gsub(vim.fn.system("git rev-parse --show-toplevel"), "\n", "") .. "/"
  require("telescope.pickers")
    .new({
      finder = require("telescope.finders").new_oneshot_job({ "git", "jump", "--stdout", "diff", "--no-relative" }, {
        entry_maker = function(line)
          local filename, lnum_string = line:match("([^:]+):(%d+).*")

          -- I couldn't find a way to use grep in new_oneshot_job so we have to filter here.
          -- return nil if filename is /dev/null because this means the file was deleted.
          if filename:match("^/dev/null") then
            return nil
          end

          return {
            path = git_root_path .. filename,
            value = filename,
            display = line,
            ordinal = line,
            filename = filename,
            lnum = tonumber(lnum_string),
          }
        end,
      }),
      sorter = require("telescope.sorters").get_generic_fuzzy_sorter(),
      previewer = require("telescope.config").values.grep_previewer({}),
      results_title = "Git hunks",
      prompt_title = "Git hunks",
      -- layout_strategy = "flex",
      layout_strategy = "vertical",
    }, {})
    :find()
end
vim.keymap.set("n", "<Leader>gh", git_hunks, {})
